package top.mcwebsite.playandroid.business.articleDetail.impl.ui

import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.Flow
import top.mcwebsite.lib.route.api.EasyRouter
import top.mcwebsite.lib.router.annotation.Param
import top.mcwebsite.lib.router.annotation.Route
import top.mcwebsite.playandroid.business.articleDetail.impl.vm.ArticleDetailIntent
import top.mcwebsite.playandroid.business.articleDetail.impl.vm.ArticleDetailUiEffect
import top.mcwebsite.playandroid.business.articleDetail.impl.vm.ArticleDetailUiState
import top.mcwebsite.playandroid.business.articleDetail.impl.vm.ArticleDetailViewModel
import top.mcwebsite.playandroid.business.articleDetail.impl.vm.OperationItem
import top.mcwebsite.playandroid.business.articleDetail.impl.vm.OperationType
import top.mcwebsite.playandroid.business.articleDetail.impl.vm.ShareItem
import top.mcwebsite.playandroid.common.constant.RouteConfig.ArticleDetail
import top.mcwebsite.playandroid.common.webview.EasyWebView
import top.mcwebsite.playandroid.common.webview.WebViewAction
import top.mcwebsite.playandroid.strings.Str

@Route("${ArticleDetail.PATH}/{${ArticleDetail.PARAM_URL}}")
@Composable
fun ArticleDetailPage(@Param("url") url: String) {
    val viewModel: ArticleDetailViewModel = viewModel()
    val uiState by viewModel.uiStateFlow.collectAsState()
    val clipboardManager = LocalClipboardManager.current
    val context = LocalContext.current

    LaunchedEffect(Unit) {
        viewModel.init(url)
    }
    viewModel.HandleUiEffect {
        when (it) {
            is ArticleDetailUiEffect.NavigationBackUiEffect -> {
                EasyRouter.popBackStack()
            }

            is ArticleDetailUiEffect.CopyUrlToClipboardUiEffect -> {
                clipboardManager.setText(AnnotatedString(it.url))
                Log.d("mengchen", "clipboardManager 设置 url = ${it.url}")
                Toast.makeText(context, context.getString(Str.copy_success), Toast.LENGTH_SHORT).show()
            }

            is ArticleDetailUiEffect.OpenInDefaultBrowser -> {
                val uri = Uri.parse(it.url)
                val intent = Intent(Intent.ACTION_VIEW, uri)
                context.startActivity(intent)
            }


        }
    }
    ArticleDetailContent(url = url, uiState, viewModel.webViewActionFlow) {
        viewModel.sendIntent(it)
    }
}

@Composable
fun ArticleDetailContent(
    url: String,
    uiState: ArticleDetailUiState,
    webViewActionFlow: Flow<WebViewAction>,
    sendIntent: (ArticleDetailIntent) -> Unit,
) {
    EasyWebView(
        url,
        onClickBack = {
            sendIntent(ArticleDetailIntent.ClickBackIntent)
        },
        onClickMore = {
            sendIntent(ArticleDetailIntent.ClickMoreIntent)
        },
        actionFlow = webViewActionFlow
    ) {
        BottomSheet(uiState, sendIntent)
        FindUI(uiState, sendIntent)
    }
}

@Composable
@OptIn(ExperimentalMaterial3Api::class)
private fun BottomSheet(
    uiState: ArticleDetailUiState,
    sendIntent: (ArticleDetailIntent) -> Unit
) {
    val modalBottomSheetState = rememberModalBottomSheetState()
    LaunchedEffect(uiState.showShareBottomSheet) {
        if (uiState.showShareBottomSheet) {
            modalBottomSheetState.show()
        } else {
            modalBottomSheetState.hide()
        }
    }
    if (uiState.showShareBottomSheet) {
        ModalBottomSheet(
            onDismissRequest = {
                sendIntent(ArticleDetailIntent.DismissBottomSheetIntent)
            },
            sheetState = modalBottomSheetState
        ) {
            Column {
                Text(
                    text = stringResource(id = Str.share_article),
                    modifier = Modifier.padding(start = 12.dp, top = 12.dp, bottom = 16.dp)
                )
                ShareItemsUI(uiState.shareItems)
                OperationItemsUI(uiState.operationItems) {
                    sendIntent(ArticleDetailIntent.ClickOperationItemIntent(it))
                }
                Spacer(modifier = Modifier.height(20.dp))
            }
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun FindUI(
    uiState: ArticleDetailUiState,
    sendIntent: (ArticleDetailIntent) -> Unit
) {
    val keyboardManager = LocalSoftwareKeyboardController.current
    val focusRequester = remember {
        FocusRequester()
    }
    val focusManager = LocalFocusManager.current
    LaunchedEffect(uiState.showFindInPage) {
        if (uiState.showFindInPage) {
            keyboardManager?.show()
            focusRequester.requestFocus()
        } else {
            keyboardManager?.hide()
        }
    }
    if (uiState.showFindInPage) {
        Column(modifier = Modifier.fillMaxSize()) {
            Spacer(modifier = Modifier
                .weight(1f)
                .clickable {
                    keyboardManager?.hide()
                })
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(color = MaterialTheme.colorScheme.background),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(id = Str.close),
                    modifier = Modifier
                        .padding(5.dp)
                        .clickable { sendIntent(ArticleDetailIntent.FindCloseIntent) })

                TextField(
                    value = uiState.findKey,
                    onValueChange = {
                        sendIntent(ArticleDetailIntent.FindInputChangeIntent(it))
                    },
                    maxLines = 1,
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                    keyboardActions = KeyboardActions(
                        onSearch = {
                            focusManager.clearFocus()
                            sendIntent(ArticleDetailIntent.FindIntent)
                        }),
                    modifier = Modifier
                        .weight(1f)
                        .focusRequester(focusRequester)
                )
                IconButton(onClick = { sendIntent(ArticleDetailIntent.FindPreIntent) }) {
                    Icon(Icons.Rounded.KeyboardArrowUp, contentDescription = null)
                }
                IconButton(onClick = { sendIntent(ArticleDetailIntent.FindNextIntent) }) {
                    Icon(Icons.Rounded.KeyboardArrowDown, contentDescription = null)
                }
            }
        }
    }
}

@Composable
private fun OperationItemsUI(operationItems: List<OperationItem>, click: (OperationType) -> Unit) {
    LazyRow {
        items(operationItems.size) {
            Column(
                Modifier
                    .padding(vertical = 10.dp, horizontal = 12.dp)
                    .width(56.dp)
                    .clickable { click(operationItems[it].operationType) }
            ) {
                Box(
                    modifier = Modifier
                        .size(56.dp)
                        .background(
                            color = MaterialTheme.colorScheme.surfaceVariant,
                            shape = RoundedCornerShape(10.dp)
                        )
                        .clip(RoundedCornerShape(10.dp))
                ) {
                    Icon(
                        imageVector = operationItems[it].icon,
                        contentDescription = null,
                        modifier = Modifier
                            .size(24.dp)
                            .align(Alignment.Center)
                    )
                }
                Spacer(modifier = Modifier.height(3.dp))
                Text(
                    text = stringResource(id = operationItems[it].labelStrRes),
                    modifier = Modifier.align(Alignment.CenterHorizontally),
                    style = MaterialTheme.typography.labelSmall,
                    textAlign = TextAlign.Center
                )
            }
        }
    }
}

@Composable
private fun ShareItemsUI(shareItems: List<ShareItem>) {
    LazyRow {
        items(shareItems.size) {
            Column {
                Column(
                    Modifier
                        .padding(vertical = 10.dp, horizontal = 12.dp)
                        .width(56.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(56.dp)
                            .background(
                                color = MaterialTheme.colorScheme.surfaceVariant,
                                shape = RoundedCornerShape(10.dp)
                            )
                    ) {
                        Image(
                            painter = painterResource(id = shareItems[it].iconRes),
                            contentDescription = null,
                            modifier = Modifier
                                .size(24.dp)
                                .align(Alignment.Center)
                        )
                    }
                    Spacer(modifier = Modifier.height(3.dp))
                    Text(
                        text = stringResource(id = shareItems[it].labelStrRes),
                        modifier = Modifier.align(Alignment.CenterHorizontally),
                        style = MaterialTheme.typography.labelSmall,
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}